package com.example.forum.services.impl;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.dao.ArticleMapper;
import com.example.forum.dao.ArticleReplyMapper;
import com.example.forum.exception.ApplicationException;
import com.example.forum.model.Article;
import com.example.forum.model.ArticleReply;
import com.example.forum.services.IArticleReplyService;
import com.example.forum.services.IArticleService;
import com.example.forum.utils.StringUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleReplyServiceImpl implements IArticleReplyService {

    @Resource
    ArticleReplyMapper articleReplyMapper;

    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private IArticleService articleService;
    @Override
    public void create(ArticleReply articleReply) {
        if (articleReply == null || articleReply.getArticleId() == null
                || articleReply.getPostUserId() == null
                || StringUtil.isEmpty(articleReply.getContent())) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new RuntimeException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        // 设置默认值
        articleReply.setReplyCount(0);
        articleReply.setLikeCount(0);
        articleReply.setState((byte) 0);
        articleReply.setDeleteState((byte) 0);
        Date now = new Date();
        articleReply.setCreateTime(now);
        articleReply.setUpdateTime(now);
        int row = articleReplyMapper.insert(articleReply);
        if (row != 1) {
            log.warn("创建文章回复失败");
            throw new RuntimeException("创建文章回复失败");
        }
        // 更新帖子表的回复数
        articleService.addOneReplyCountById(articleReply.getArticleId());
        log.info("创建文章回复成功，文章id:{}，用户id:{}", articleReply.getArticleId(), articleReply.getPostUserId());


    }

    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {
        if (articleId == null || articleId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new RuntimeException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        // 调用dao
        return articleReplyMapper.selectByArticleId(articleId);
    }

    @Override
    public ArticleReply selectById(Long id) {
        if (id == null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new RuntimeException(ResultCode.FAILED_PARAMS_VALIDATE.toString());
        }
        return articleReplyMapper.selectByPrimaryKey(id);
    }

    @Override
    public void addOneBuildReplyCountById(Long id) { // id 是文章回复表的id
        // 1. 校验回复是否存在
        ArticleReply articleReply = articleReplyMapper.selectByPrimaryKey(id);
        if (articleReply == null || articleReply.getDeleteState() == 1) {
            log.warn("回复ID {} 不存在或已删除", id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_COMMENT_NOT_EXISTS));
        }
        if (articleReply.getState() == 1) {
            log.warn("回复ID {} 被封禁", id);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_COMMENT_BANNED));
        }

        // 2. 获取文章ID和楼主ID
        Long articleId = articleReply.getArticleId();
        Long buildId = articleReply.getPostUserId();
        if (articleId <= 0 || buildId <= 0) {
            log.warn("无效的参数: articleId={}, buildId={}", articleId, buildId);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        // 3. 校验文章是否存在且未被删除/封禁
        Article article = articleMapper.selectByPrimaryKey(articleId);
        if (article == null || article.getDeleteState() == 1) {
            log.warn("文章ID {} 不存在或已删除", articleId);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS));
        }
        if (article.getState() == 1) {
            log.warn("文章ID {} 被封禁", articleId);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED));
        }

        // 4.更新回复表的回复数
        ArticleReply updateArticleReply = new ArticleReply();
        updateArticleReply.setId(articleReply.getId());
        updateArticleReply.setReplyCount(articleReply.getReplyCount() + 1);
        updateArticleReply.setUpdateTime(new Date());

        // 5.同步更新文章回复数
        articleService.addOneReplyCountById(articleReply.getArticleId());

        int row = articleReplyMapper.updateByPrimaryKeySelective(updateArticleReply);
        if (row != 1) {
            log.error("更新回复数失败，影响行数{}", row);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }
}
